import {
  getProcessByPage,
  addProcess,
  updateProcess,
  delProcess,
  exportProcess,
} from '@/services/baseData/process';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Select } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from '@/components/dayjs';
const Process: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const dateFormat = 'YYYY-MM-DD';
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',

      width: 140,
      align: 'center',
      sorter: true,
    },
    {
      title: '工序名称',
      dataIndex: 'processName',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '是否生产工序',
      dataIndex: 'isProductionProcess',
      search: false,
      align: 'center',
      sorter: true,
      width: 140,
      render: (text, record, _, action) => {
        return <div>{record.isProductionProcess == 1 ? '是' : '否'}</div>;
      },
    },
    {
      title: '是否需要自检',
      dataIndex: 'showSelfInspection',
      search: false,
      align: 'center',
      sorter: true,
      width: 140,
      render: (text, record, _, action) => {
        return <div>{record.showSelfInspection == 1 ? '是' : '否'}</div>;
      },
    },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    //   search: false,
    // },
    {
      title: '创建人', //表头显示的名称
      search: false,
      width: 130,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      width: 150,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      render: (text, record, _, action) => {
        return dayjs(record.createTime).format(dateFormat);
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 160,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              memo: record.memo,
              processCode: record.processCode,
              processName: record.processName,
              reserved: record.reserved,
              serialNo: record.serialNo,
              id: record.id,
              isProductionProcess: record.isProductionProcess == 1 ? '是' : '否',
              showSelfInspection: record.showSelfInspection == 1 ? '是' : '否',
            });
          }}
        >
          编辑工序
        </a>,
        // <a
        //   key="deleteKey"
        //   onClick={() => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定要删除吗',
        //       okText: '确认',
        //       cancelText: '取消',
        //       onOk: async () => {
        //         await delProcess({ id: record.id });
        //         actionRef.current!.reload();
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          if (res.processName.length < 20) {
            const result = await addProcess(res);
            if (result != null) {
              message.success('添加成功');
              setConfirmLoading(false);
              setModalVisit(false);
              actionRef.current!.reload();
            }
          } else {
            message.warning('工序名称过长');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.isProductionProcess =
            res.isProductionProcess == '是'
            ? 1
            : res.isProductionProcess == '否'
            ? 0
            : res.isProductionProcess;
          res.showSelfInspection =
            res.showSelfInspection == '是'
            ? 1
            : res.showSelfInspection == '否'
            ? 0
            : res.showSelfInspection;
          console.log(res);
          if (res.processName.length < 20) {
            const result = await updateProcess(res);
            if (result != null) {
              message.success('修改成功');
              setConfirmLoading(false);
              setModalVisit(false);
              actionRef.current!.reload();
            }
          } else {
            message.warning('工序名称过长');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="工序定义"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportProcess({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `Process.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          const result = await getProcessByPage({ ...params, sorters: sorters, filters: filters });
          // console.log(result.data.content);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1000, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        width={600}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="工序编号" name="processCode" hidden={!createOrUpdate}>
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="工序名称"
            name="processName"
            rules={[{ required: true, message: '请输入工序名称!' }]}
          >
            <Input maxLength={20} showCount allowClear />
          </Form.Item>
          <Form.Item
            label="是否生产工序"
            name="isProductionProcess"
            rules={[{ required: true, message: '请选择是否生产工序!' }]}
          >
            <Select
              defaultValue="请选择"
              options={[
                { value: '1', label: '是' },
                { value: '0', label: '否' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="是否需要自检"
            name="showSelfInspection"
            rules={[{ required: true, message: '请选择是否需要自检!' }]}
          >
            <Select
              defaultValue="请选择"
              options={[
                { value: '1', label: '是' },
                { value: '0', label: '否' },
              ]}
            />
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input allowClear />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default Process;
